package com.dalanmao.netty2;

import android.util.Log;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Created by MENRED-WHB on 2016/10/28.
 */

public class TimeClient {


    private Channel channel;
    private EventLoopGroup group;


    public void connect(String host, int port) {


        group = new NioEventLoopGroup();


        try {

            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new NettyClientHandler());
                            pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        }
                    });
            ChannelFuture f = bootstrap.connect(host, port).sync();
//            f.channel().closeFuture().sync();
            channel = f.channel();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            group.shutdownGracefully();
        }

    }


    public void sendMessage(String msg) {//连接成功后，通过Channel提供的接口进行IO操作
        try {
            if (channel != null && channel.isOpen()) {


                byte[] req = msg.getBytes();

                req = yiHuo(req);


                ByteBuf firstMessage = Unpooled.buffer(req.length);

                firstMessage.writeBytes(req);


                channel.writeAndFlush(firstMessage).sync();


                Log.i("zl", "成功发送 " + msg);
            } else {
                throw new Exception("channel is null | closed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public byte[] yiHuo(byte[] k) {
        byte[] tem = new byte[k.length];
        for (int i = 0; i < k.length; i++) {
            tem[i] = (byte) (k[i] ^ 0xa1);
        }
        return tem;
    }


    public void close() {
        try {
            group.shutdownGracefully();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
